import os
import re
import threading
from collections import defaultdict

import numpy as np
import time

from openpyxl.drawing.image import Image

from commen.log import Logger
import openpyxl
# import commen.config
from tools.draw_pic import draw_single_picture, draw_multiple_picture


def output_result(result_data, interval=10):
    total = 0
    total_number = 0
    for t, num in sorted(result_data.items()):
        if int(t) > 1000000:
            continue
        print(f"{t}ms:{num}个")
        total += int(t) * num
        total_number += num
    standard = total_number * interval
    print(f"总数：{total_number}")
    if total / standard < 1:
        print(f"{interval}ms连续率：{round((total / standard)*100,2)}%")
    else:
        print(f"{interval}ms连续率：{round((standard / total)*100,2)}%")


def output_picture(imu_timestamp, imu_timestamp_interval, time_now):
    # save_path = "./picture" + os.sep + f"{time_now}"
    draw_single_picture(x_array=range(len(imu_timestamp_interval)), y_array=imu_timestamp_interval,
                        title='IMU continuation',
                        y_lable='timestamp interval(ms)', hline=10)
    # save_path=save_path + os.sep + 'IMU continuation.png'
    draw_single_picture(x_array=range(len(imu_timestamp)), y_array=imu_timestamp, title='IMU continuation',
                        y_lable='timestamp')

    interval_zoom = [0, len(imu_timestamp_interval), 8, 13]
    draw_single_picture(x_array=range(len(imu_timestamp_interval)), y_array=imu_timestamp_interval,
                        title=f'IMU continuation(zoom{interval_zoom})',
                        y_lable='timestamp interval(ms)', zoom_size=interval_zoom, hline=10)

    timestamp_zoom = [0, len(imu_timestamp), imu_timestamp[-1] - 10 * len(imu_timestamp), imu_timestamp[-1] + 100]
    draw_single_picture(x_array=range(len(imu_timestamp)), y_array=imu_timestamp,
                        title=f'IMU continuation(zoom{timestamp_zoom})',
                        y_lable='timestamp', zoom_size=timestamp_zoom)


def output_mutipicture(imu_timestamp, imu_timestamp_interval, time_now):
    save_path = "./picture" + os.sep + f"{time_now}" + 'IMU_continuation_muti.png'
    (x_array_list := [range(len(imu_timestamp_interval)), range(len(imu_timestamp))]).extend(x_array_list)
    (y_array_list := [imu_timestamp_interval, imu_timestamp]).extend(y_array_list)
    (y_label_array_list := ['timestamp interval(ms)', 'timestamp']).extend(y_label_array_list)
    title = 'IMU continuation'
    zoom_config = {2: (8, 13), 3: (imu_timestamp[-1] - 10 * len(imu_timestamp), imu_timestamp[-1] + 100)}
    hline_config = {0: 10, 2: 10}
    draw_multiple_picture(x_array_list, y_array_list, title, y_label_array_list, zoom_config=zoom_config,
                          hline_config=hline_config, save_path=save_path)
    return save_path


def ImuDatacontinuity():
    # ---------读取config文件获取筛选字段内容--------------------------
    # key = commen.config.global_config.getRaw('keywords', 'Imubegincontinuation')
    key = "to_timestamp(147) imu"
    # ---------读取config文件获取筛选字段内容--------------------------
    # -----------------------创建excel--------------------------------------------
    # 获取当前时间
    time_now = time.strftime("%Y%m%d-%H%M", time.localtime())
    # 获取当前路径
    result_root = os.getcwd()
    root = os.getcwd()
    result_path = result_root + r'\result' + "\\" + time_now
    log_path = root + r'\original-logfile' + '\\'
    # -----遍历对比log路径获取要对比的文件名路径信息----------------------
    for root, dirs, files in os.walk(log_path):
        for file in files:
            if "Data" in file:
                aa = os.path.join(root, file)
    # -----遍历对比log路径获取要对比的文件名路径信息----------------------
    book = openpyxl.Workbook()  # 打开一个将写的文件
    sheet = book.create_sheet(index=0)  # 在将写的文件创建sheet
    saveExcel = result_path + "imu连续性验证结果.xlsx"
    sheet.cell(1, 2).value = "log_DataProc系统时间"
    sheet.cell(1, 3).value = "原值"
    sheet.cell(1, 4).value = "减值"
    sheet.cell(1, 5).value = "连续性差值"

    row = 1
    # -----------------------创建excel--------------------------------------------

    logger = Logger(logger='TestMylog').getlog()
    fm = open(aa, 'r', encoding='UTF-8')  # 打开目标文件
    logger.info("打开目标文件")
    lines = fm.readlines()
    logger.info("获取内容")
    num = 0
    log_DataProctime_list = []
    imutime_list = []
    list = []
    logger.info("开始逐行读取")

    for lines in lines:  # 对内容 进行逐行读取

        if key in lines:  # kye是读取config文件获取的筛选字段
            num = num + 1
            bbxitongtime = lines[:lines.index("<thread")]  # 根据关键字“log_mcucomm”截取前面的系统时间戳
            e = lines[lines.rfind(key):lines.rfind('(0)')]
            e = e[e.rfind(key):e.rfind('(42)')]
            e = e[e.rfind(key):e.rfind('(10)')]
            e = e[e.rfind(key):e.rfind('(52)')]
            aatime = e.split(key)
            imutime_list.append(aatime[1])
            aa = lines.split("=>")  # 截取数据=>末尾的字符串时间戳
            try:
                list.append(aa[1])  # 追加到list中
            except:
                print(1)
            log_DataProctime_list.append(bbxitongtime)
    logger.info("开始判断差值")
    picture_data = []
    picture_time = []
    disc = defaultdict(int)
    for i in range(len(list)):
        if int(i) + 2 > len(list):  # 执行到最后一个之后跳出循环
            break
        # elif str(int(list[int(i) + 1]) - int(list[i])) in disc:
        #     logger.info("开始计算差值：" + str(list[int(i) + 1]) + "-" + str(list[i]) + "=" + str(
        #         int(list[int(i) + 1]) - int(list[i])))
        #     disc[str(int(list[int(i) + 1]) - int(list[i]))] = int(disc[str(int(list[int(i) + 1]) - int(list[i]))]) + 1
        #     row = row + 1
        #     time2 = log_DataProctime_list[i].rstrip()
        #     time2 = time2.lstrip()  # 删除字符串前面的空格
        #     time3 = imutime_list[i].rstrip()  # 删除字符串后面的空格
        #     time3 = time3.lstrip()
        #     time4 = imutime_list[int(i) + 1].rstrip()
        #     time4 = time4.lstrip()
        #     sheet.cell(row, 2).value = str(time2)
        #     sheet.cell(row, 3).value = str(time3)
        #     sheet.cell(row, 4).value = str(time4)
        #     sheet.cell(row, 5).value = str(int(list[int(i) + 1]) - int(list[i]))
        #     value_data = int(list[int(i) + 1]) - int(list[i])
        #     # if 100 > value_data:
        #     picture_data.append(value_data)
        #     picture_time.append(int(list[i]))
        #
        # else:
        #     logger.info("开始计算差值：" + str(list[int(i) + 1]) + "-" + str(list[i]) + "=" + str(
        #         int(list[int(i) + 1]) - int(list[i])))
        #     disc[str(int(list[int(i) + 1]) - int(list[i]))] = 1
        #     row = row + 1
        #     time2 = log_DataProctime_list[i].rstrip()
        #     time2 = time2.lstrip()  # 删除字符串前面的空格
        #     time3 = imutime_list[i].rstrip()  # 删除字符串后面的空格
        #     time3 = time3.lstrip()
        #     time4 = imutime_list[int(i) + 1].rstrip()
        #     time4 = time4.lstrip()
        #     sheet.cell(row, 2).value = str(time2)
        #     sheet.cell(row, 3).value = str(time3)
        #     sheet.cell(row, 4).value = str(time4)
        #     sheet.cell(row, 5).value = str(int(list[int(i) + 1]) - int(list[i]))
        #     value_data = int(list[int(i) + 1]) - int(list[i])
        #     # if 100 > value_data:
        #     picture_data.append(value_data)
        #     picture_time.append(int(list[i]))

        logger.info("开始计算差值：" + str(list[int(i) + 1]) + "-" + str(list[i]) + "=" + str(
            int(list[int(i) + 1]) - int(list[i])))
        disc[int(list[int(i) + 1]) - int(list[i])] += 1
        row = row + 1
        time2 = log_DataProctime_list[i].rstrip()
        time2 = time2.lstrip()  # 删除字符串前面的空格
        time3 = imutime_list[i].rstrip()  # 删除字符串后面的空格
        time3 = time3.lstrip()
        time4 = imutime_list[int(i) + 1].rstrip()
        time4 = time4.lstrip()
        sheet.cell(row, 2).value = str(time2)
        sheet.cell(row, 3).value = str(time3)
        sheet.cell(row, 4).value = str(time4)
        sheet.cell(row, 5).value = str(int(list[int(i) + 1]) - int(list[i]))
        value_data = int(list[int(i) + 1]) - int(list[i])
        # if 100 > value_data:
        picture_data.append(value_data)
        picture_time.append(int(list[i]))
    # output_picture(imu_timestamp=picture_time, imu_timestamp_interval=picture_data, time_now=time_now)
    picture_path = output_mutipicture(imu_timestamp=picture_time, imu_timestamp_interval=picture_data,
                                      time_now=time_now)
    print(disc)
    output_result(disc, 10)
    (sheet2 := book.create_sheet(index=1)).add_image(Image(picture_path))
    sheet2.title = 'imu连续性趋势图'
    # ----------------------将对比的数据写入excel---------------------------------
    book.save(saveExcel)
    # input("按任意键继续。。。。")
    # ----------------------将对比的数据写入excel---------------------------------


ImuDatacontinuity()
